/*
 * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */
package com.sun.lwuit;

import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.plaf.Style;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Rectangle;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.DefaultListCellRenderer;
import com.sun.lwuit.list.DefaultListModel;
import com.sun.lwuit.list.ListCellRenderer;
import com.sun.lwuit.list.ListModel;
import com.sun.lwuit.plaf.UIManager;
import java.util.Vector;

/**
 * A combo box is a list that allows only one selection at a time, when a user clicks
 * the combo box a popup button with the full list of elements allows the selection of
 * a single element. The combo box is driven by the list model and allows all the renderer
 * features of the List as well. 
 * 
 * @see List
 * @author Chen Fishbein
 */
public class ComboBox extends List {

    private static String id = "ComboBox";
    private Component popupContent;
    private List contained;
    private Popup popup;

    /** 
     * Creates a new instance of ComboBox 
     * 
     * @param items set of items placed into the combo box model
     */
    public ComboBox(Vector items) {
        this(new DefaultListModel(items));
    }

    /** 
     * Creates a new instance of ComboBox 
     * 
     * @param items set of items placed into the combo box model
     */
    public ComboBox(Object[] items) {
        this(new DefaultListModel(items));
    }

    /** 
     * Constructs an empty combo box
     */
    public ComboBox() {
        this(new DefaultListModel());
    }

    /**
     * Creates a new instance of ComboBox 
     * 
     * @param model the model for the combo box elements and selection
     */
    public ComboBox(ListModel model) {
        super(model);
        ((DefaultListCellRenderer) super.getRenderer()).setShowNumbers(false);
        setInputOnFocus(false);
        setIsScrollVisible(false);
        setFixedSelection(FIXED_NONE_CYCLIC);
    }

    /**
     * @inheritDoc
     */
    public int getBaseline(int width, int height) {
        Component selected;
        if (getRenderingPrototype() != null) {
            selected = getRenderer().getListCellRendererComponent(this, getRenderingPrototype(), 0, true);
        }
        if (getModel().getSize() > 0) {
            selected = getRenderer().getListCellRendererComponent(this, getModel().getItemAt(0), 0, true);
        } else {
            selected = getRenderer().getListCellRendererComponent(this, "XXXXXXXXXXX", 0, true);
        }
        return getHeight() - getStyle().getPadding(BOTTOM) - selected.getStyle().getPadding(BOTTOM);
    }

    /**
     * @inheritDoc
     */
    protected String getUIID() {
        return id;
    }

    /**
     * @inheritDoc
     */
    public void setSelectedIndex(int selection) {
        super.setSelectedIndex(selection, false);
    }

    /**
     * @inheritDoc
     */
    public void setSelectedIndex(int selection, boolean scroll) {
        super.setSelectedIndex(selection, false);
    }

    /**
     * @inheritDoc
     */
    public void setModel(ListModel m) {
        super.setModel(m);
        if (contained != null) {
            contained.setModel(m);
        }
    }

    /**
     * @inheritDoc
     */
    public void setHandlesInput(boolean handlesInput) {
        super.setHandlesInputParent(handlesInput);
        getPopup().setVisible(handlesInput);
        if (isSmoothScrolling()) {
            if (handlesInput) {
                getComponentForm().registerAnimated(contained);
                contained.setSelectedIndex(contained.getSelectedIndex(), true);
            } else {
                getComponentForm().deregisterAnimated(contained);
            }
        }
    }

    /**
     * @inheritDoc
     */
    public void setSmoothScrolling(boolean smoothScrolling) {
        super.setSmoothScrolling(smoothScrolling);
        if (contained != null) {
            contained.setSmoothScrolling(smoothScrolling);
        }
    }

    /**
     * @inheritDoc
     */
    protected void fireClicked() {
        setHandlesInput(!handlesInput());
    }

    private Component getPopupContent() {

        contained = createPopupList();
        contained.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                setHandlesInput(!handlesInput());
                fireActionEvent();
            }
        });
        Container cnt = new Container(new BorderLayout());
        cnt.addComponent(BorderLayout.CENTER, contained);
        cnt.layoutContainer();
        popupContent = cnt;
        return popupContent;
    }

    /**
     * Creates the list object used within the popup dialog. This method allows subclasses
     * to customize the list creation for the popup dialog shown when the combo box is pressed.
     * 
     * @return a newly created list object used when the user presses the combo box.
     */
    protected List createPopupList() {
        List l = new List(getModel()) {

            protected void fireClicked() {
                ComboBox.this.setHandlesInput(!ComboBox.this.handlesInput());
                ComboBox.this.fireActionEvent();
            }

            public void keyPressed(int keyCode) {
                if (Display.getInstance().getGameAction(keyCode) == Display.GAME_LEFT ||
                        Display.getInstance().getGameAction(keyCode) == Display.GAME_RIGHT) {
                    return;
                }
                super.keyPressed(keyCode);
            }

            public void keyReleased(int keyCode) {
                if (Display.getInstance().getGameAction(keyCode) == Display.GAME_LEFT ||
                        Display.getInstance().getGameAction(keyCode) == Display.GAME_RIGHT) {
                    return;
                }
                super.keyReleased(keyCode);
            }
        };
        l.setSmoothScrolling(isSmoothScrolling());
        l.setFixedSelection(getFixedSelection());
        l.setListCellRenderer(getRenderer());
        l.setSelectedStyle(UIManager.getInstance().getComponentStyle("ComboBoxPopup"));

        return l;
    }

    private Popup getPopup() {
        if (popup == null) {
            popup = new Popup(getComponentForm(), getPopupContent());
        } else {
            contained.setListCellRenderer(getRenderer());
            contained.setModel(getModel());
        }
        int y = getAbsoluteY() + getHeight();
        int height = Math.min(getComponentForm().getHeight() - y, popupContent.getPreferredSize().getHeight());

        // if there is not enough room to popup, open the popup upwards.
        if (getComponentForm().getHeight() - y < contained.getElementSize(true).getHeight() * 3) {
            height = contained.getElementSize(true).getHeight() * 3;
            y = getAbsoluteY() - height;
        }
        popupContent.setHeight(height);
        popupContent.setX(getAbsoluteX());
        popupContent.setY(y);
        popupContent.setWidth(getWidth());
        popupContent.setFixedPosition(true);
        Style s = popupContent.getStyle();
        s.merge(getUnselectedStyle());
        s.setBgTransparency(0xFF);
        s.setBorder(null);
        s.setMargin(0, 0, 0, 0);
        s.setPadding(0, 0, 0, 0);
        return popup;
    }

    /**
     * Reset popup data on model change to allow the popup to refresh with the 
     * right details
     * 
     * @param status the model status
     */
    protected void modelChanged(int status) {
        popup = null;
        popupContent = null;
    }

    /**
     * Prevent the combo box from losing selection in some use cases
     */
    void selectElement(int selectedIndex) {
    }

    /**
     * @inheritDoc
     */
    public void pointerReleased(int x, int y) {
        setHandlesInput(true);
    }

    /**
     * @inheritDoc
     */
    public void paint(Graphics g) {
        UIManager.getInstance().getLookAndFeel().drawComboBox(g, this);
    }

    /**
     * @inheritDoc
     */
    protected Dimension calcPreferredSize() {
        return UIManager.getInstance().getLookAndFeel().getComboBoxPreferredSize(this);
    }
}
